import { Login } from "@/api/login.js";
import { setToken, setUsername, getToken, getUsername, removeToken, removeUsername } from "@/utils/app.js";
const state = {
  navIsCollapse: JSON.parse(localStorage.getItem('navIsCollapse')) || false,
  token: getToken() || "",
  username: getUsername() || ""
};

const getters = {};

const mutations = {
  setNavCollapse (state) {
    state.navIsCollapse = !state.navIsCollapse;
    // console.log(state);
    localStorage.setItem('navIsCollapse', JSON.stringify(state.navIsCollapse));
  },
  // 设置token
  setToken (state, value) {
    state.token = value;
  },
  setUsername (state, value) {
    state.username = value;
  }
};
const actions = {
  loginSyn (content, requestData) {
    return new Promise((resolve, reject) => {
      Login(requestData)
        .then(response => {
          let data = response.data.data;
          // vuex存储
          content.commit("setToken", data.token);
          content.commit("setUsername", data.username);
          // cookie存储
          setToken(data.token);
          setUsername(data.username);

          resolve(response);
        }).catch(error => {
          reject(error);
        })
    });
  },
  // 退出登录
  exit (content) {
    return new Promise((resolve, reject) => {
      // 清除cookie
      removeToken();
      removeUsername();
      // 清除本地数据
      content.commit("setToken","");
      content.commit("setUsername","");
      resolve();
    });
  }

};

export default {
  namespaced: true, // 启用命名空间模式
  state,
  getters,
  mutations,
  actions
};
